import os
import pandas as pd
import plotly.graph_objects as go

def lineplot(df_plot,line_plot,save_path,method):
    # fig = make_subplots(specs=[[{"secondary_y": True}]])

    # # Add'保费','理赔预测' to the primary y-axis
    # for plt in bar_plot:
    #     fig.add_trace(go.Bar(x=df_plot.index, 
    #                         y=df_plot[plt].values, 
    #                         name=plt),
    #                 secondary_y=False)

    # # Add '当期赔付','累计赔付' to the secondary y-axis
    # for plt in line_plot:
    #     fig.add_trace(go.Scatter(x=df_plot.index, 
    #                         y=df_plot[plt].values, 
    #                         name=plt),
    #                 secondary_y=True)
    # 生成画布对象
    fig = go.Figure()  

    # 添加多个图形轨迹
    for i in range(len(line_plot)):
        fig.add_trace(go.Scatter(x=df_plot.index, y= df_plot[line_plot[i]], name= line_plot[i]))

    fig.update_layout(
        autosize=False,
        width=1800,
        height=600,
        title = f'{method}当期vs累计赔付情况',
        xaxis_title = 'Time',
        yaxis_title = '赔付情况',
        font = dict(size = 8),
        template = 'plotly_white' #"plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"
    )
    fig.update_xaxes(dtick="M3")#tickvals=df_plot.index, ticktext=pd.to_datetime(df_plot.index).to_series().dt.strftime('%Y-%m'), 
    fig.update_layout(yaxis_range=[0,150])
    fig.update_traces(mode="lines+markers")

    # Add range slider
    fig.update_layout(
        xaxis=dict(
            rangeselector=dict(
                buttons=list([
                    dict(count=1,
                        label="1m",
                        step="month",
                        stepmode="backward"),
                    dict(count=6,
                        label="6m",
                        step="month",
                        stepmode="backward"),
                    dict(count=1,
                        label="YTD",
                        step="year",
                        stepmode="todate"),
                    dict(count=1,
                        label="1y",
                        step="year",
                        stepmode="backward"),
                    dict(step="all")
                ])
            ),
            rangeslider=dict(
                visible=True
            ),
            type="date"
        )
    )


    fig.write_html(f'{save_path}\\lineplot.html')

def barplot(df_plot,bar_plot,save_path):

    # 生成画布对象
    fig = go.Figure()  

    # 添加多个图形轨迹
    for i in range(len(bar_plot)):
        fig.add_trace(go.Bar(x=df_plot.index, y= df_plot[bar_plot[i]], name= bar_plot[i]))

    fig.update_layout(
        autosize=False,
        width=1800,
        height=600,
        title = '保费vs理赔预测情况',
        xaxis_title = 'Time',
        yaxis_title = '',
        font = dict(size = 10),
        template = 'plotly_white' #"plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"
    )
    fig.update_xaxes(dtick="M3")#tickvals=df_plot.index, ticktext=pd.to_datetime(df_plot.index).to_series().dt.strftime('%Y-%m'), 


    # Add range slider
    fig.update_layout(
        xaxis=dict(
            rangeselector=dict(
                buttons=list([
                    dict(count=1,
                        label="1m",
                        step="month",
                        stepmode="backward"),
                    dict(count=6,
                        label="6m",
                        step="month",
                        stepmode="backward"),
                    dict(count=1,
                        label="YTD",
                        step="year",
                        stepmode="todate"),
                    dict(count=1,
                        label="1y",
                        step="year",
                        stepmode="backward"),
                    dict(step="all")
                ])
            ),
            rangeslider=dict(
                visible=True
            ),
            type="date"
        )
    )
    fig.write_html(f'{save_path}\\barplot.html')

def plot_all(df_baofei,df_jingfei,df_lp,save_path,method):
    updates = pd.concat([df_baofei,df_jingfei],axis=1)
    # updates.rename(columns={0:'保费',1:'理赔预测'},inplace=True)
    updates.columns = ['保费','理赔预测']
    updates.index = updates.index.set_names('月份')

    lp_bymonth = df_lp[['维修申请时间','理赔金额']]#,'主承保共保比例'TODO
    # lp_bymonth['理赔金额'] = lp_bymonth['理赔金额'] * lp_bymonth['主承保共保比例']
    lp_summary = lp_bymonth.groupby('维修申请时间')['理赔金额'].sum().sort_index()
    lp_summary.index = lp_summary.index.set_names('月份')

    final = pd.concat([updates,lp_summary],axis=1).sort_index()
    final.rename(columns={'理赔金额':'实际理赔'},inplace=True)
    final['实际/预测'] = final['实际理赔']/final['理赔预测']
    final.loc[:,'综合实际理赔'] = final['理赔预测'].values
    final.loc[lp_summary.index,'综合实际理赔'] = final.loc[lp_summary.index,'实际理赔']

    final['当期赔付'] =100*final['综合实际理赔']/final['保费']
    final['累计赔付'] = 100*final['综合实际理赔'].cumsum()/final['保费'].cumsum()

    lineplot_list = ['当期赔付','累计赔付']
    barplot_list = ['保费','综合实际理赔']
    df_plot = final.loc[final.index>'2009-01-01'].copy(deep=True) #TODO 苏宁大陆人保项目开始时间

    lineplot(df_plot,lineplot_list,save_path,method)
    barplot(df_plot,barplot_list,save_path)
    df_plot.to_csv(os.path.join(save_path,f'{method}toplot.csv'))